package com.cqupt.sendMes.utils;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.cqupt.sendMes.enums.HttpStatusEnum;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class HttpUtils {
    private final String BASE_URL = "https://wxpusher.zjiecode.com";
    // 定义 JSON 媒体类型
    private final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    //全局header
    Headers headers = new Headers.Builder().add("Accept", "application/json").build();

    /**
     * Post请求
     * */
    public String post(String path, Object body){
        if(ObjectUtil.isNull(body)){
            log.warn("请求体为空，退出请求");
            return null;
        }
        String url = BASE_URL + path;
        String bodyStr = JSONObject.toJSONString(body);

        RequestBody requestBody = FormBody.create(bodyStr, JSON);
        //组装post请求对象
        Request postRequest = new Request.Builder()
                .url(url)
                .headers(headers)
                .post(requestBody)
                .build();
        return doExecute(postRequest);
    }

    /**
     * get请求
     * */
    public String get(String path, Map<String, Object> data){
        //组装请求url
        String url = BASE_URL + path;
        if(!ObjectUtil.isNull(data)) {
            url = url + "?" + parseMap2Query(data);
        }
        log.info("构建完成的url:{}", url);

        //构建Request对象
        Request request = new Request.Builder()
                .url(url)
                .headers(headers)
                .build();
        //执行
        return doExecute(request);
    }

    /**
     * 把map转成GET查询的参数形式
     */
    // 将Map对象转换为查询字符串
    private String parseMap2Query(Map<String, Object> data) {
        // 如果data为空，则返回null
        if (ObjectUtil.isNull(data)) {
            return null;
        }
        // 获取data中的所有键值对
        Set<Map.Entry<String, Object>> entries = data.entrySet();
        StringBuilder stringBuilder = new StringBuilder();
        // 遍历键值对
        for (Map.Entry<String, Object> entry : entries) {
            // 如果StringBuilder不为空，则添加一个&符号
            if (stringBuilder.length() > 0) {
                stringBuilder.append("&");
            }
            // 将键和值添加到StringBuilder中
            stringBuilder.append(entry.getKey()).append("=").append(entry.getValue());
        }
        // 返回查询字符串
        return stringBuilder.toString();
    }


    public String doExecute(Request request){
        //创建OkHttpClient对象
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
        try{
            //发送请求
            Response response = client.newCall(request).execute();
            int resCode = response.code();
            if(resCode == HttpStatusEnum.SUCCESS.getCode()){
                if (ObjectUtil.isNotNull(response.body())) {
                    return response.body().string();
                } else {
                    log.warn("返回有误，返回体为空");
                }
            }else {
                log.warn("请求失败，响应码为{}",resCode);
            }
        } catch (IOException e) {
            log.warn("请求失败，请检查网络");
        }
        return null;
    }
}
